package test.zdx.杂七杂八;

public class MyLinkedList0
{
    public MyLinkedList0() {
    }
    private int size =0;
    Node head = null;



    public int get(int index)
    {
        if(index < 0 || index >=this.size)
        {
            System.out.println("都他喵越界了你搁这儿查个JB呢");
            return -1;
        }
        Node cur = this.head;
        int cnt=-1;
        while(cur != null)
        {
            cnt++;
            if(cnt == index)
            {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;

    }

    public void addAtHead(int val)
    {//不论空结点头插法还是非空，都记得size加一。
        Node node = new Node(val);
        if(head == null)
        {
            this.head = node;
            this.size++;
            return ;
        }
        node.next = this.head.next;
        this.size++;
    }

    public void addAtTail(int val)
    {
        Node node = new Node(val);
        if(this.head == null)
        {
            this.head = node;
            this.size++;
            return;
        }
        //这时候设置链表长度的妙处就出来了。
        Node cur = this.head;
        while(cur != null)
        {
            if(cur.next==null)
            {
                this.size++;
                cur.next=node;
            }
            cur = cur.next;
        }
    }

    public void addAtIndex(int index, int val)
    {
        if(index == 0) addAtHead(val);
        if(index == this.size)  addAtTail(val);
        if(index<0 || index>size )
        {
            System.out.println("都越界了你搁这儿插Jb呢？");
            return;
        }
        int cnt = -1;
        Node cur = head;
        Node node = new Node(val);
        while(head != null)
        {
            cnt++;
            if(cnt == index-1)
            {
                node.next=cur.next;
                cur.next = node;
                this.size++;
                return;
            }
            cur = cur.next;
        }
    }

    public void deleteAtIndex(int index)
    {
        if(index < 0 || index>=this.size)
        {
            System.out.println("你搁这儿删个jb呢，越界了都！");
            return;
        }
        int cnt = -1;
        Node cur = this.head;
        while(cur != null)
        {
            cnt++;
            if(cnt == index-1)
            {
                this.size--;
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
        }

    }

    public void clear()
    {
        this.head = null;
        this.size = 0;
    }

    public void printList()
    {
        Node cur =this.head;
        while(cur != null)
        {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
    }
}




class Node
{
    public Node(int val)//搞结点这个类一定要有构造方法啊，官方给的是：
    {
        this.val= val;
    }
    public int val;
    Node next = null;
}

